<template>
  <div class="my-houses-container">
    <h2>我的出租房源</h2>
    <el-table :data="houseList" style="width: 100%">
      <el-table-column prop="house_id" label="房源ID" width="80" />
      <el-table-column prop="photo_url" label="图片" width="120">
        <template #default="scope">
          <el-image
            :src="formatImageUrl(scope.row.photo_url)"
            style="width: 100px; height: 80px; object-fit: cover;"
            fit="cover"
          >
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
                <span>暂无图片</span>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="monthly_rent" label="月租金" width="100" />
      <el-table-column prop="rental_method" label="出租方式" width="80" />
      <el-table-column prop="house_type" label="户型" width="100" />
      <el-table-column prop="floor_area" label="面积(㎡)" width="100" />
      <el-table-column prop="orientation" label="朝向" width="80" />
      <el-table-column prop="decoration" label="装修" width="80" />
      <el-table-column prop="district" label="区域" width="100" />
      <el-table-column prop="address" label="详细地址" />
      <el-table-column prop="status" label="状态" width="80" />
      <!-- 新增租客信息列 -->
      <el-table-column label="租客" width="120">
        <template #default="scope">
          <span
            v-if="scope.row.status === '出租中'"
            style="color: #409EFF; cursor: pointer;"
            @click="showTenantInfo(scope.row.tenant_id)"
          >
            {{ scope.row.tenant_name }}
          </span>
          <span v-else>-
          </span>
        </template>
      </el-table-column>
      <!-- 结束新增租客信息列 -->
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-bar">
      <el-button :disabled="page === 1" @click="changePage(page - 1)">上一页</el-button>
      <span>第 {{ page }} / {{ totalPages }} 页</span>
      <el-button :disabled="page === totalPages" @click="changePage(page + 1)">下一页</el-button>
      <el-button type="primary" @click="goBack" style="margin-bottom: 16px;">返回(Esc)</el-button>
    </div>

    <!-- 编辑房源信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑房源信息" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="描述"><el-input v-model="editForm.description" /></el-form-item>
        <el-form-item label="月租金"><el-input v-model="editForm.monthly_rent" type="number" /></el-form-item>
        <el-form-item label="出租方式">
          <el-select v-model="editForm.rental_method" placeholder="请选择">
            <el-option label="合租" value="合租" />
            <el-option label="整租" value="整租" />
          </el-select>
        </el-form-item>
        <el-form-item label="户型"><el-input v-model="editForm.house_type" /></el-form-item>
        <el-form-item label="面积"><el-input v-model="editForm.floor_area" type="number" /></el-form-item>
        <el-form-item label="朝向">
          <el-select v-model="editForm.orientation" placeholder="请选择">
            <el-option label="东" value="东" />
            <el-option label="南" value="南" />
            <el-option label="西" value="西" />
            <el-option label="北" value="北" />
            <el-option label="东南" value="东南" />
            <el-option label="西北" value="西北" />
            <el-option label="东北" value="东北" />
            <el-option label="东南" value="东南" />
          </el-select>
        </el-form-item>
        <el-form-item label="装修">
          <el-select v-model="editForm.decoration" placeholder="请选择">
            <el-option label="精装" value="精装" />
            <el-option label="简装" value="简装" />
            <el-option label="毛坯" value="毛坯" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域"><el-input v-model="editForm.district" /></el-form-item>
        <el-form-item label="详细地址"><el-input v-model="editForm.address" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option label="闲置" value="闲置" />
            <el-option label="出租中" value="出租中" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增租客信息弹窗 -->
    <el-dialog v-model="tenantInfoDialogVisible" title="租客信息" width="400px">
      <p><strong>姓名:</strong> {{ tenantInfo.account_name }}</p>
      <p><strong>电话:</strong> {{ tenantInfo.phone }}</p>
      <template #footer>
        <el-button @click="tenantInfoDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 结束新增租客信息弹窗 -->

  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const goBack = () => {
  if (route.query.returnTo) {
    router.push({
      path: '/user',
      query: { activeTab: route.query.returnTo }
    })
  } else {
    router.push('/user')
  }
}

// 全局键盘事件处理函数
const handleKeydown = (e) => {
  // 处理Esc快捷键
  if (e.key === 'Escape') {
    e.preventDefault() // 阻止默认行为
    goBack()
  }
}

const houseList = ref([])
const editDialogVisible = ref(false)
const editForm = ref({})
const page = ref(1)
const perPage = ref(5)
const totalPages = ref(1)

// 新增租客信息相关的响应式数据
const tenantInfoDialogVisible = ref(false)
const tenantInfo = ref({ account_name: '', phone: '' })
// 结束新增租客信息相关的响应式数据

const fetchMyHouses = async () => {
  const token = localStorage.getItem('token')
  const res = await axios.get('http://127.0.0.1:5000/api/landlord/my-houses', {
    headers: { Authorization: `Bearer ${token}` },
    params: { page: page.value, per_page: perPage.value }
  })
  if (res.data.status === 200) {
    houseList.value = res.data.data
    totalPages.value = res.data.pagination.total_pages || 1
  }
}

const changePage = (newPage) => {
  if (newPage < 1 || newPage > totalPages.value) return
  page.value = newPage
  fetchMyHouses()
}

const openEditDialog = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

const submitEdit = async () => {
  const token = localStorage.getItem('token')
  const houseId = editForm.value.house_id
  const res = await axios.put(`http://127.0.0.1:5000/api/landlord/my-houses/${houseId}`, editForm.value, {
    headers: { Authorization: `Bearer ${token}` }
  })
  if (res.data.status === 200) {
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    fetchMyHouses()
  } else {
    ElMessage.error(res.data.msg || '修改失败')
  }
}

const formatImageUrl = (photoUrl) => {
  if (!photoUrl) return ''
  if (photoUrl.startsWith('http://') || photoUrl.startsWith('https://')) {
    return photoUrl
  }
  return `http://127.0.0.1:5000/static/house-img/${photoUrl}`
}

// 新增显示租客信息的方法
const showTenantInfo = async (tenantId) => {
  if (!tenantId) return
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get(`http://127.0.0.1:5000/api/users/tenant-info/${tenantId}`, {
      headers: { Authorization: `Bearer ${token}` }
    })
    if (res.data.status === 200) {
      tenantInfo.value = res.data.data
      tenantInfoDialogVisible.value = true
    } else {
      ElMessage.error(res.data.msg || '获取租客信息失败')
    }
  } catch (error) {
    ElMessage.error('获取租客信息时发生错误')
    console.error('Error fetching tenant info:', error)
  }
}
// 结束新增显示租客信息的方法

onMounted(() => {
  fetchMyHouses()
  
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  // 移除全局键盘事件监听
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.my-houses-container { padding: 30px; }
.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 80px;
  color: #bbb;
  font-size: 14px;
}
.pagination-bar {
  margin: 20px 0 0 0;
  display: flex;
  align-items: center;
  gap: 16px;
}
:deep(.el-table__header th) {
  background: linear-gradient(90deg, #1976d2 0%, #64b5f6 100%);
  color: #fff;
}
</style>